package com.example.managemyself.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * 文件工具类
 * 处理多媒体文件的显示、播放和打开
 */
public class FileUtil {
    
    private static final String TAG = "FileUtil";
    
    /**
     * 加载图片到ImageView
     */
    public static void loadImageIntoView(ImageView imageView, String imagePath) {
        try {
            File imageFile = new File(imagePath);
            if (imageFile.exists()) {
                // 压缩加载图片以避免内存溢出
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2; // 压缩比例
                options.inJustDecodeBounds = false;
                
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                } else {
                    imageView.setImageResource(android.R.drawable.ic_menu_gallery);
                }
            } else {
                imageView.setImageResource(android.R.drawable.ic_menu_gallery);
            }
        } catch (Exception e) {
            imageView.setImageResource(android.R.drawable.ic_menu_gallery);
        }
    }
    
    /**
     * 加载视频缩略图
     */
    public static void loadVideoThumbnail(ImageView imageView, String videoPath) {
        try {
            File videoFile = new File(videoPath);
            if (videoFile.exists()) {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                try {
                    retriever.setDataSource(videoPath);
                    Bitmap bitmap = retriever.getFrameAtTime(1000000); // 获取第1秒的帧
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                    } else {
                        imageView.setImageResource(android.R.drawable.ic_media_play);
                    }
                } finally {
                    retriever.release();
                }
            } else {
                imageView.setImageResource(android.R.drawable.ic_media_play);
            }
        } catch (Exception e) {
            imageView.setImageResource(android.R.drawable.ic_media_play);
        }
    }
    
    /**
     * 播放视频
     */
    public static void playVideo(Context context, String videoPath) {
        try {
            File videoFile = new File(videoPath);
            if (videoFile.exists()) {
                Uri videoUri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".fileprovider", videoFile);
                
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(videoUri, "video/*");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "没有找到可以播放视频的应用", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "视频文件不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, "播放视频失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 播放音频
     */
    public static void playAudio(Context context, String audioPath) {
        try {
            File audioFile = new File(audioPath);
            if (audioFile.exists()) {
                Uri audioUri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".fileprovider", audioFile);
                
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(audioUri, "audio/*");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "没有找到可以播放音频的应用", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "音频文件不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, "播放音频失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 打开文件
     */
    public static void openFile(Context context, String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                Uri fileUri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".fileprovider", file);
                
                Intent intent = new Intent(Intent.ACTION_VIEW);
                
                // 根据文件扩展名设置MIME类型
                String mimeType = getMimeType(filePath);
                intent.setDataAndType(fileUri, mimeType);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "没有找到可以打开此文件的应用", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, "打开文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 根据文件路径获取MIME类型
     */
    private static String getMimeType(String filePath) {
        String extension = getFileExtension(filePath).toLowerCase();
        
        switch (extension) {
            case "pdf":
                return "application/pdf";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case "ppt":
                return "application/vnd.ms-powerpoint";
            case "pptx":
                return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            case "txt":
                return "text/plain";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "mp4":
                return "video/mp4";
            case "mp3":
                return "audio/mpeg";
            case "wav":
                return "audio/wav";
            default:
                return "application/octet-stream";
        }
    }
    
    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String filePath) {
        int lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < filePath.length() - 1) {
            return filePath.substring(lastDotIndex + 1);
        }
        return "";
    }
    
    /**
     * 获取文件大小（格式化显示）
     */
    public static String getFormattedFileSize(long sizeBytes) {
        if (sizeBytes < 1024) {
            return sizeBytes + " B";
        } else if (sizeBytes < 1024 * 1024) {
            return String.format("%.1f KB", sizeBytes / 1024.0);
        } else if (sizeBytes < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", sizeBytes / (1024.0 * 1024.0));
        } else {
            return String.format("%.1f GB", sizeBytes / (1024.0 * 1024.0 * 1024.0));
        }
    }
    
    /**
     * 检查文件是否存在
     */
    public static boolean fileExists(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return false;
        }
        File file = new File(filePath);
        return file.exists() && file.isFile();
    }
    
    /**
     * 删除文件
     */
    public static boolean deleteFile(String filePath) {
        try {
            File file = new File(filePath);
            return file.exists() && file.delete();
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 获取文件名（不包含路径）
     */
    public static String getFileName(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return "";
        }
        File file = new File(filePath);
        return file.getName();
    }
} 